package cn.oms.oms.service.impl;

import cn.oms.oms.entity.*;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.*;
import cn.oms.oms.service.IOrderService;
import cn.oms.oms.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private EmrMapper emrMapper;

    @Autowired
    private DruginfoMapper druginfoMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private PrescriptionMapper prescriptionMapper;

    /**
     * 根据查询条件查询医嘱列表列表
     * @param orderVo
     * @return
     */
    @Override
    public PageInfo<Order> selectOrderList(OrderVo orderVo) {

        QueryWrapper<Order> query = new QueryWrapper<>();
        // 如果医嘱号不为空，新增查询条件 医嘱号或病历号或处方号
        if (orderVo.getOrderId()!=null&&!"".equals(orderVo.getOrderId())){
            query.eq("orderId",orderVo.getOrderId())
                    .or().eq("emrId",orderVo.getOrderId())
                    .or().eq("prescriptionId",orderVo.getOrderId());
        }

        //如果患者名称不为空，新增查询条件 患者名称或患者ID
        if (StringUtil.isNotEmpty(orderVo.getPatientName())){
            query.like("patientName",orderVo.getPatientName())
                    .or().eq("patientId",orderVo.getPatientName());
        }

        //如果产品名称不为空，新增查询条件 产品名称或产品ID
        if (StringUtil.isNotEmpty(orderVo.getItemName())){
            // 先查询产品 模糊查询产品名称或产品ID
            QueryWrapper<Item> query1 = new QueryWrapper<>();
            query1.like("itemName",orderVo.getItemName())
                    .or().like("itemNameSN",orderVo.getItemName())
                    .or().like("ingredientName",orderVo.getItemName());
            query1.eq("deleteFlag",0);
            List<Item> items = itemMapper.selectList(query1);
            List<Integer> itemIdList = new ArrayList<>();
            //如果查得到产品
            if (items.size() <= 0&&items!=null){
                for (Item item: items) {
                    itemIdList.add(item.getItemId());
                }
            }
            if (itemIdList.size()>0&&itemIdList!=null){
                query.in("itemId",itemIdList);
            }
        }

        //如果处方号不为空 新增查询条件 处方号
        if(orderVo.getPrescriptionId()!=null&&!"".equals(orderVo.getPrescriptionId())){
            query.eq("prescriptionId",orderVo.getPrescriptionId());
        }

        // 如果签名标记不为空 新增查询条件 签名标记
        if (orderVo.getDoctorSignatureFlag()!=null&&!"".equals(orderVo.getDoctorSignatureFlag())){
            query.eq("doctorSignatureFlag",orderVo.getDoctorSignatureFlag());
        }

        // 查询条件 未删除
        query.eq("deleteFlag",0);

        //分页
        PageHelper.startPage(orderVo.getPageNum(),orderVo.getPageSize());
        List<Order> orders = orderMapper.selectList(query);
        if (orders==null){
            throw new ServiceException("未查询到医嘱,或医嘱为空");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //根据医嘱数据 格式化
        for (Order order: orders) {
            // 更新产品名称
            QueryWrapper<Item> query1 = new QueryWrapper<>();
            query1.eq("itemId",order.getItemId());
            query1.eq("deleteFlag",0);
            Item item = itemMapper.selectOne(query1);
            if (item!=null){
                order.setReturnItemName(item.getItemName());
            }

            //格式化时间
           order.setReturnCreateTime(simpleDateFormat.format(order.getCreateTime()));
        }

        return new PageInfo<>(orders);
    }

    /**
     * 根据医嘱ID查询医嘱详情
     * @param orderVo
     * @return
     */
    @Override
    public Order selectOrderDetail(OrderVo orderVo) {

        if (orderVo.getOrderId()==null|"".equals(orderVo.getOrderId())){
            throw new ServiceException("参数异常，医嘱ID为空");
        }
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("orderId",orderVo.getOrderId());
        query.eq("deleteFlag",0);
        Order order = orderMapper.selectOne(query);
        if (order==null){
            throw new ServiceException("参数异常，未查询到医嘱信息");
        }
        // 日期格式化
        order.setReturnCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateTime()));

        // 更新产品名称
        QueryWrapper<Item> query1 = new QueryWrapper<>();
        query1.eq("itemId",order.getItemId());
        query1.eq("deleteFlag",0);
        Item item = itemMapper.selectOne(query1);
        if (item!=null){
            order.setReturnItemName(item.getItemName());
        }

        System.out.println("order = " + order);
        return order;
    }

    /**
     * 新增医嘱
     * @param orderVo
     * @return
     */
    @Override
    public String addOrder(OrderVo orderVo) {
        if (orderVo.getEmrId()==null|"".equals(orderVo.getEmrId())){
            throw new ServiceException("参数异常，病历ID为空");
        }
        Order order = new Order();

        // 根据病历ID查询病历
        QueryWrapper<Emr> query = new QueryWrapper<>();
        query.eq("emrId",orderVo.getEmrId());
        query.eq("deleteFlag",0);
        Emr emr = emrMapper.selectOne(query);
        if (emr==null){
            throw new ServiceException("参数异常，电子病历不存在");
        }
        order.setEmrId(emr.getEmrId());
        order.setPatientId(emr.getPatientId());
        order.setPatientName(emr.getPatientName());

        if (orderVo.getItemId()==null|"".equals(orderVo.getItemId())){
            throw new ServiceException("参数异常，库存ID为空");
        }

        order.setItemId(orderVo.getItemId());

        // 根据产品ID查询库存产品基本单位
        QueryWrapper<Druginfo> query1 = new QueryWrapper<>();
        query1.eq("itemId",orderVo.getItemId());
        query1.eq("deleteFlag",0);
        Druginfo druginfo = druginfoMapper.selectOne(query1);
        if (druginfo==null){
            throw new ServiceException("参数异常，药品库存信息不存在");
        }
        order.setSendDoseUnitName(druginfo.getUnitName());

        //发药量处理
        if (orderVo.getSendDose()==null||"".equals(orderVo.getSendDose())){
            throw new ServiceException("参数异常，发药量不能为空");
        }
        //先更改库存 再做下一步操作
        //判断库存量是否充足
        BigDecimal sendDose = orderVo.getSendDose();
        int sendDoseInt = sendDose.intValue();
        Integer sendDosege = Integer.valueOf(sendDoseInt);
        int returnNum = sendDosege.compareTo(druginfo.getAvailableQty());
        // 返回1说明存量小于当前需要量
        if (returnNum==1){
            throw new ServiceException("参数异常，库存不足！！！请重试");
        }
        //扣减库存
        druginfo.setAvailableQty(druginfo.getAvailableQty()-sendDosege);
        //新增冻结量
        druginfo.setFreezeQty(druginfo.getFreezeQty()+sendDosege);
        // 修改库存信息
        int num = druginfoMapper.updateById(druginfo);
        if (num!=1){
            throw new ServiceException("数据库修改异常，库存量修改异常！！！");
        }
        order.setSendDose(orderVo.getSendDose());

        // 插入频次等信息
        order.setFrequencyDetail(orderVo.getFrequencyDetail());
        order.setSupplementaryFrequencyDetail(orderVo.getSupplementaryFrequencyDetail());
        order.setMealTimeDetail(orderVo.getMealTimeDetail());


        // 医嘱签名为0
        order.setDoctorSignatureFlag(0);

        // 查询患者是否有处方单
        // 若没有处方单则创建处方单 ，若有处方单则直接绑定处方单
        QueryWrapper<Prescription> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emrId",orderVo.getEmrId());
        queryWrapper.eq("vetFlag",0);
        queryWrapper.eq("deleteFlag",0);
        queryWrapper.orderByDesc("createTime");
        List<Prescription> prescriptionList = prescriptionMapper.selectList(queryWrapper);
        //如果为true说明有未审处方，则直接拿到处方号执行绑定
        if (prescriptionList.size()>0&&prescriptionList!=null){
            order.setPrescriptionId(prescriptionList.get(0).getPrescriptionId());
        }else {
            //否则 执行新增处方操作再进行插入
            Prescription prescription1 = new Prescription();
            // 根据病历号查询患者信息
            QueryWrapper<Emr> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("emrId",orderVo.getEmrId());
            queryWrapper1.eq("deleteFlag",0);
            Emr emr1 = emrMapper.selectOne(queryWrapper1);
            if (emr1==null){
                throw new ServiceException("数据库修改异常，电子病历信息不存在");
            }
            prescription1.setPatientId(emr1.getPatientId());
            prescription1.setPatientName(emr1.getPatientName());
            prescription1.setEmrId(emr1.getEmrId());
            prescription1.setVetFlag(0);
            prescription1.setCreateTime(new Date());
            prescription1.setDeleteFlag(0);
            int insert = prescriptionMapper.insert(prescription1);
            if (insert!=1){
                throw new ServiceException("数据库新增异常，新增处方失败");
            }
            order.setPrescriptionId(prescription1.getPrescriptionId());

        }
        order.setCreateTime(new Date());
        order.setDeleteFlag(0);

        num = orderMapper.insert(order);

        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }

    /**
     * 修改医嘱
     * @param orderVo
     * @return
     */
    @Override
    public String updateOrder(OrderVo orderVo) {

        // 判断医嘱ID是否未空
        if (orderVo.getOrderId()==null||"".equals(orderVo.getOrderId())){
            throw new ServiceException("参数异常，医嘱ID不能为空");
        }
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("orderId",orderVo.getOrderId());
        query.eq("deleteFlag",0);
        Order order = orderMapper.selectOne(query);
        if (order==null){
            throw new ServiceException("参数异常，未找到医嘱信息");
        }

        //判断医嘱是否签名，若签名无法更改医嘱
        if (order.getDoctorSignatureFlag()==1){
            throw new ServiceException("医嘱已签名，无法修改！！！");
        }

        // 判断产品是否更改
        if (order.getItemId().compareTo(orderVo.getItemId())==0){
            //若等于0 说明没有更改产品

            //判断发药量是否更改
            if (order.getSendDose().compareTo(orderVo.getSendDose())==0){
                //如果为0说明没有更改则不做任何修改
            }else {
                /**
                 * 未完待续，进行退药退费操作
                 */
            }

            if (StringUtil.isNotEmpty(orderVo.getFrequencyDetail())){
                order.setFrequencyDetail(orderVo.getFrequencyDetail());
            }
            if (StringUtil.isNotEmpty(orderVo.getSupplementaryFrequencyDetail())){
                order.setSupplementaryFrequencyDetail(orderVo.getSupplementaryFrequencyDetail());
            }
            if (StringUtil.isNotEmpty(orderVo.getMealTimeDetail())){
                order.setMealTimeDetail(orderVo.getMealTimeDetail());
            }

        }else {
            /**
             * 未完待续
             */
            //否则 说明更改了产品，则进行退药退费 ，再进行重新划产品

        }

//        int num = orderMapper.updateById(order);
//        if (num!=1){
//            throw new ServiceException("数据库新增异常！！！");
//        }
//
//        return "ok";

        return null;
    }

    /**
     * 删除医嘱
     * @param id
     * @return
     */
    @Override
    public String deleteOrder(Integer id) {
        if (id==null||"".equals(id)){
            throw new ServiceException("参数异常，医嘱Id不能为空");
        }
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("orderId",id);
        query.eq("deleteFlag",0);
        Order order = orderMapper.selectOne(query);
        if (order==null){
            throw new ServiceException("参数异常，未找到医嘱信息");
        }
        // 判断医嘱是否签名
        if (order.getDoctorSignatureFlag()==1){
            throw new ServiceException("医嘱已签名，无法删除");
        }

        order.setDeleteFlag(1);
        int num = orderMapper.updateById(order);

        if (num!=1){
            throw new ServiceException("数据库修改异常！！！");
        }

        return "ok";
    }

    /**
     * 医嘱签名
     * @param orderVo
     * @return
     */
    @Override
    public String orderSignature(OrderVo orderVo) {
        if (orderVo.getOrderId()==null||"".equals(orderVo.getOrderId())){
            throw new ServiceException("参数异常，医嘱Id不能为空");
        }
        if (orderVo.getDoctorSignatureFlag()==null||"".equals(orderVo.getDoctorSignatureFlag())){
            throw new ServiceException("参数异常，签名标记不能为空");
        }
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("orderId",orderVo.getOrderId());
        query.eq("deleteFlag",0);
        Order order = orderMapper.selectOne(query);
        if (order==null){
            throw new ServiceException("参数异常，未找到医嘱信息");
        }

        order.setDoctorSignatureFlag(orderVo.getDoctorSignatureFlag());
        int num = orderMapper.updateById(order);

        if (num!=1){
            throw new ServiceException("数据库修改异常！！！");
        }

        return "ok";
    }

    /**
     * 医嘱批量签名
     * @param orderVo
     * @return
     */
    @Override
    public String orderSignatureList(OrderVo orderVo) {
        if (orderVo.getOrderId()==null||"".equals(orderVo.getOrderId())){
            throw new ServiceException("参数异常，医嘱Id不能为空");
        }
        if (orderVo.getDoctorSignatureFlag()==null||"".equals(orderVo.getDoctorSignatureFlag())){
            throw new ServiceException("参数异常，签名标记不能为空");
        }
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("orderId",orderVo.getOrderId());
        query.eq("deleteFlag",0);
        Order order = orderMapper.selectOne(query);
        if (order==null){
            throw new ServiceException("参数异常，未找到医嘱信息");
        }

        //根据医嘱号查处方
        QueryWrapper<Prescription> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prescriptionId",order.getPrescriptionId());
        queryWrapper.eq("deleteFlag",0);
        Prescription prescription = prescriptionMapper.selectOne(queryWrapper);
        if (prescription==null){
            throw new ServiceException("参数异常，未找到处方信息");
        }
        //根据处方号查所有医嘱
        QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("prescriptionId",prescription.getPrescriptionId());
        queryWrapper1.eq("deleteFlag",0);
        List<Order> orderList = orderMapper.selectList(queryWrapper1);
        if (orderList.size()>0&&orderList!=null){
            for (Order order1:orderList){
                order1.setDoctorSignatureFlag(orderVo.getDoctorSignatureFlag());
                int num = orderMapper.updateById(order1);
                if (num!=1){
                    throw new ServiceException("数据库修改异常！！！");
                }
            }
        }

        return "ok";
    }
}
